<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>perlsyn - Perl syntax - Perldoc Browser</title>
    <link rel="search" href="https://perldoc.perl.org/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser">
    <link rel="canonical" href="https://perldoc.perl.org/perlsyn">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" />
    <style>
      body {
        background: #f4f4f5;
        color: #020202;
      }
      .navbar-dark {
        background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%);
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0);
        background-repeat: repeat-x;
      }
      .navbar-dark .navbar-nav .nav-link,
      .navbar-dark .navbar-nav .nav-link:focus { color: #fff }
      .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 }
      #wrapperlicious {
        margin: 0 auto;
        font: 0.9em 'Helvetica Neue', Helvetica, sans-serif;
        font-weight: normal;
        line-height: 1.5em;
        margin: 0;
        padding: 0;
      }
      #wrapperlicious h1 { font-size: 1.5em }
      #wrapperlicious h2 { font-size: 1.3em }
      #wrapperlicious h3 { font-size: 1.1em }
      #wrapperlicious h4 { font-size: 0.9em }
      #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3,
      #wrapperlicious h4, #wrapperlicious dt {
        color: #020202;
        margin-top: 1em;
        margin-bottom: 1em;
        position: relative;
        font-weight: bold;
      }
      #wrapperlicious a { color: inherit; text-decoration: underline }
      #wrapperlicious #toc { text-decoration: none }
      #wrapperlicious a:hover { color: #2a2a2a }
      #wrapperlicious a img { border: 0 }
      #wrapperlicious :not(pre) > code {
        color: inherit;
        background-color: rgba(0, 0, 0, 0.04);
        border-radius: 3px;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        padding: 0.3em;
      }
      #wrapperlicious dd {
        margin: 0;
        margin-left: 2em;
      }
      #wrapperlicious dt {
        color: #2a2a2a;
        font-weight: bold;
        margin-left: 0.9em;
      }
      #wrapperlicious p {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious li > p {
        margin-bottom: 0;
        margin-top: 0;
      }
      #wrapperlicious pre {
        border: 1px solid #c1c1c1;
        border-radius: 3px;
        font: 100% Consolas, Menlo, Monaco, monospace;
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious pre > code {
        display: block;
        background-color: #f6f6f6;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        line-height: 1.5em;
        text-align: left;
        white-space: pre;
        padding: 1em;
      }
      #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious ul {
        list-style-type: square;
      }
      #wrapperlicious ul ul {
        margin-bottom: 0px;
        margin-top: 0px;
      }
      #footer {
        font-size: 0.8em;
        padding-top: 0.5em;
        text-align: center;
      }
      #more {
        display: inline;
        font-size: 0.8em;
      }
      #perldocdiv {
        background-color: #fff;
        border: 1px solid #c1c1c1;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        margin-left: auto;
        margin-right: auto;
        padding: 3em;
        padding-top: 1em;
        max-width: 960px;
      }
      #moduleversion { float: right }
      #wrapperlicious .leading-notice {
        font-style: italic;
        padding-left: 1em;
        margin-top: 1em;
        margin-bottom: 1em;
      }
      #wrapperlicious .permalink {
        display: none;
        left: -0.75em;
        position: absolute;
        padding-right: 0.25em;
        text-decoration: none;
      }
      #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink,
      #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink,
      #wrapperlicious dt:hover .permalink {
        display: block;
      }
    </style>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-KVNWBNT5FB');
      gtag('config', 'UA-50555-3');
    </script>
  </head>
  <body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="https://perldoc.perl.org/">Perldoc Browser</a>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlsyn.html#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">5.35.0</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-stable">
          <a class="dropdown-item" href="https://perldoc.perl.org/perlsyn">Latest</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.2/perlsyn">5.38.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.1/perlsyn">5.38.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0/perlsyn">5.38.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.3/perlsyn">5.36.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.2/perlsyn">5.36.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.1/perlsyn">5.36.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.0/perlsyn">5.36.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.3/perlsyn">5.34.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.2/perlsyn">5.34.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.1/perlsyn">5.34.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.0/perlsyn">5.34.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.1/perlsyn">5.32.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.0/perlsyn">5.32.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.3/perlsyn">5.30.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.2/perlsyn">5.30.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.1/perlsyn">5.30.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.0/perlsyn">5.30.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.3/perlsyn">5.28.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.2/perlsyn">5.28.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.1/perlsyn">5.28.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.0/perlsyn">5.28.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.3/perlsyn">5.26.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.2/perlsyn">5.26.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.1/perlsyn">5.26.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.0/perlsyn">5.26.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.4/perlsyn">5.24.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.3/perlsyn">5.24.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.2/perlsyn">5.24.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.1/perlsyn">5.24.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.0/perlsyn">5.24.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.4/perlsyn">5.22.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.3/perlsyn">5.22.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.2/perlsyn">5.22.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.1/perlsyn">5.22.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.0/perlsyn">5.22.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.3/perlsyn">5.20.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.2/perlsyn">5.20.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.1/perlsyn">5.20.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.0/perlsyn">5.20.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.4/perlsyn">5.18.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.3/perlsyn">5.18.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.2/perlsyn">5.18.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.1/perlsyn">5.18.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.0/perlsyn">5.18.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.3/perlsyn">5.16.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.2/perlsyn">5.16.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.1/perlsyn">5.16.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.0/perlsyn">5.16.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.4/perlsyn">5.14.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.3/perlsyn">5.14.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.2/perlsyn">5.14.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.1/perlsyn">5.14.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.0/perlsyn">5.14.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.5/perlsyn">5.12.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.4/perlsyn">5.12.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.3/perlsyn">5.12.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.2/perlsyn">5.12.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.1/perlsyn">5.12.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.0/perlsyn">5.12.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.1/perlsyn">5.10.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.0/perlsyn">5.10.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.9/perlsyn">5.8.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.8/perlsyn">5.8.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.7/perlsyn">5.8.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.6/perlsyn">5.8.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.5/perlsyn">5.8.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.4/perlsyn">5.8.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.3/perlsyn">5.8.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.2/perlsyn">5.8.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.1/perlsyn">5.8.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.0/perlsyn">5.8.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.2/perlsyn">5.6.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.1/perlsyn">5.6.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.0/perlsyn">5.6.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_04/perlsyn">5.005_04</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_03/perlsyn">5.005_03</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_02/perlsyn">5.005_02</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_01/perlsyn">5.005_01</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005/perlsyn">5.005</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlsyn.html#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-dev">
          <a class="dropdown-item" href="https://perldoc.perl.org/blead/perlsyn">blead</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.6/perlsyn">5.39.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.5/perlsyn">5.39.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.4/perlsyn">5.39.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.3/perlsyn">5.39.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.2/perlsyn">5.39.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.1/perlsyn">5.39.1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC2/perlsyn">5.38.0-RC2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC1/perlsyn">5.38.0-RC1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.11/perlsyn">5.37.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.10/perlsyn">5.37.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.9/perlsyn">5.37.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.8/perlsyn">5.37.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.7/perlsyn">5.37.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.6/perlsyn">5.37.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.5/perlsyn">5.37.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.4/perlsyn">5.37.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.3/perlsyn">5.37.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.2/perlsyn">5.37.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.1/perlsyn">5.37.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.0/perlsyn">5.37.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.11/perlsyn">5.35.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.10/perlsyn">5.35.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.9/perlsyn">5.35.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.8/perlsyn">5.35.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.7/perlsyn">5.35.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.6/perlsyn">5.35.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.5/perlsyn">5.35.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.4/perlsyn">5.35.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.3/perlsyn">5.35.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.2/perlsyn">5.35.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.1/perlsyn">5.35.1</a>
          <a class="dropdown-item active" href="perlsyn.html">5.35.0</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlsyn.html#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-nav">
          <a class="dropdown-item" href="perl.html">Perl</a>
          <a class="dropdown-item" href="perlintro.html">Intro</a>
          <a class="dropdown-item" href="perl.html#Tutorials">Tutorials</a>
          <a class="dropdown-item" href="perlfaq.html">FAQs</a>
          <a class="dropdown-item" href="perl.html#Reference-Manual">Reference</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlop.html">Operators</a>
          <a class="dropdown-item" href="functions.html">Functions</a>
          <a class="dropdown-item" href="variables.html">Variables</a>
          <a class="dropdown-item" href="modules.html">Modules</a>
          <a class="dropdown-item" href="perlutil.html">Utilities</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlcommunity.html">Community</a>
          <a class="dropdown-item" href="perlhist.html">History</a>
        </div>
      </li>
    </ul>
    <ul class="navbar-nav">
      <script>
        function set_expand (expand) {
          var perldocdiv = document.getElementById('perldocdiv');
          var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width');
          var expanded = (width == '' || width == 'none') ? true : false;
          if (expand === null) {
            expand = !expanded;
          }
          if ((expand && !expanded) || (!expand && expanded)) {
            perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px');
            var button_classlist = document.getElementById('content-expand-button').classList;
            if (expand) {
              button_classlist.add('btn-light');
              button_classlist.remove('btn-outline-light');
            } else {
              button_classlist.add('btn-outline-light');
              button_classlist.remove('btn-light');
            }
          }
          return expand;
        }
        function toggle_expand () {
          var expand = set_expand(null);
          document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC';
        }
        function read_expand () {
          return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 });
        }
        if (document.readyState === 'loading') {
          document.addEventListener('DOMContentLoaded', function () {
            if (read_expand()) {
              set_expand(true);
            }
          });
        } else if (read_expand()) {
          set_expand(true);
        }
      </script>
      <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-2" onclick="toggle_expand()">Expand</button>
    <ul>
    <form class="form-inline" method="get" action="https://perldoc.perl.org/5.35.0/search">
      <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search">
    </form>
  </div>
</nav>

    <div id="wrapperlicious" class="container-fluid">
      <div id="perldocdiv">
        <div id="links">
          <a href="perlsyn.html">perlsyn</a>
          <div id="more">
            (<a href="perlsyn.txt">source</a>,
            <a href="https://metacpan.org/pod/perlsyn">CPAN</a>)
          </div>
        </div>
        <div class="leading-notice">
          You are viewing the version of this documentation from Perl 5.35.0.
            This is a development version of Perl.
        </div>
        <h1><a id="toc">CONTENTS</a></h1>
                  <ul>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#NAME">NAME </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#DESCRIPTION">DESCRIPTION</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#Declarations">Declarations    </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#Comments">Comments  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#Simple-Statements">Simple Statements    </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#Statement-Modifiers">Statement Modifiers         </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#Compound-Statements">Compound Statements               </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#Loop-Control">Loop Control      </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#For-Loops">For Loops  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#Foreach-Loops">Foreach Loops  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#Try-Catch-Exception-Handling">Try Catch Exception Handling  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#Basic-BLOCKs">Basic BLOCKs </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#Switch-Statements">Switch Statements</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#Goto">Goto </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#The-Ellipsis-Statement">The Ellipsis Statement           </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#PODs:-Embedded-Documentation">PODs: Embedded Documentation  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#Plain-Old-Comments-(Not!)">Plain Old Comments (Not!)     </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#Experimental-Details-on-given-and-when">Experimental Details on given and when</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#Breaking-out">Breaking out</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#Fall-through">Fall-through</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#Return-value">Return value</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#Switching-in-a-loop">Switching in a loop</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlsyn.html#Differences-from-Raku">Differences from Raku</a>
              </li>
          </ul>

              </li>
          </ul>

              </li>
          </ul>

      <h1 id="NAME"><a class="permalink" href="perlsyn.html#NAME">#</a>NAME </h1>

<p>perlsyn - Perl syntax</p>

<h1 id="DESCRIPTION"><a class="permalink" href="perlsyn.html#DESCRIPTION">#</a>DESCRIPTION</h1>

<p>A Perl program consists of a sequence of declarations and statements which run from the top to the bottom. Loops, subroutines, and other control structures allow you to jump around within the code.</p>

<p>Perl is a <b>free-form</b> language: you can format and indent it however you like. Whitespace serves mostly to separate tokens, unlike languages like Python where it is an important part of the syntax, or Fortran where it is immaterial.</p>

<p>Many of Perl&#39;s syntactic elements are <b>optional</b>. Rather than requiring you to put parentheses around every function call and declare every variable, you can often leave such explicit elements off and Perl will figure out what you meant. This is known as <b>Do What I Mean</b>, abbreviated <b>DWIM</b>. It allows programmers to be <b>lazy</b> and to code in a style with which they are comfortable.</p>

<p>Perl <b>borrows syntax</b> and concepts from many languages: awk, sed, C, Bourne Shell, Smalltalk, Lisp and even English. Other languages have borrowed syntax from Perl, particularly its regular expression extensions. So if you have programmed in another language you will see familiar pieces in Perl. They often work the same, but see <a href="perltrap.html">perltrap</a> for information about how they differ.</p>

<h2 id="Declarations"><a class="permalink" href="perlsyn.html#Declarations">#</a>Declarations    </h2>

<p>The only things you need to declare in Perl are report formats and subroutines (and sometimes not even subroutines). A scalar variable holds the undefined value (<code>undef</code>) until it has been assigned a defined value, which is anything other than <code>undef</code>. When used as a number, <code>undef</code> is treated as <code>0</code>; when used as a string, it is treated as the empty string, <code>&quot;&quot;</code>; and when used as a reference that isn&#39;t being assigned to, it is treated as an error. If you enable warnings, you&#39;ll be notified of an uninitialized value whenever you treat <code>undef</code> as a string or a number. Well, usually. Boolean contexts, such as:</p>

<pre><code>if ($a) {}</code></pre>

<p>are exempt from warnings (because they care about truth rather than definedness). Operators such as <code>++</code>, <code>--</code>, <code>+=</code>, <code>-=</code>, and <code>.=</code>, that operate on undefined variables such as:</p>

<pre><code>undef $a;
$a++;</code></pre>

<p>are also always exempt from such warnings.</p>

<p>A declaration can be put anywhere a statement can, but has no effect on the execution of the primary sequence of statements: declarations all take effect at compile time. All declarations are typically put at the beginning or the end of the script. However, if you&#39;re using lexically-scoped private variables created with <code>my()</code>, <code>state()</code>, or <code>our()</code>, you&#39;ll have to make sure your format or subroutine definition is within the same block scope as the my if you expect to be able to access those private variables.</p>

<p>Declaring a subroutine allows a subroutine name to be used as if it were a list operator from that point forward in the program. You can declare a subroutine without defining it by saying <code>sub name</code>, thus: </p>

<pre><code>sub myname;
$me = myname $0             or die &quot;can&#39;t get myname&quot;;</code></pre>

<p>A bare declaration like that declares the function to be a list operator, not a unary operator, so you have to be careful to use parentheses (or <code>or</code> instead of <code>||</code>.) The <code>||</code> operator binds too tightly to use after list operators; it becomes part of the last element. You can always use parentheses around the list operators arguments to turn the list operator back into something that behaves more like a function call. Alternatively, you can use the prototype <code>($)</code> to turn the subroutine into a unary operator:</p>

<pre><code>sub myname ($);
$me = myname $0             || die &quot;can&#39;t get myname&quot;;</code></pre>

<p>That now parses as you&#39;d expect, but you still ought to get in the habit of using parentheses in that situation. For more on prototypes, see <a href="perlsub.html">perlsub</a>.</p>

<p>Subroutines declarations can also be loaded up with the <code>require</code> statement or both loaded and imported into your namespace with a <code>use</code> statement. See <a href="perlmod.html">perlmod</a> for details on this.</p>

<p>A statement sequence may contain declarations of lexically-scoped variables, but apart from declaring a variable name, the declaration acts like an ordinary statement, and is elaborated within the sequence of statements as if it were an ordinary statement. That means it actually has both compile-time and run-time effects.</p>

<h2 id="Comments"><a class="permalink" href="perlsyn.html#Comments">#</a>Comments  </h2>

<p>Text from a <code>&quot;#&quot;</code> character until the end of the line is a comment, and is ignored. Exceptions include <code>&quot;#&quot;</code> inside a string or regular expression.</p>

<h2 id="Simple-Statements"><a class="permalink" href="perlsyn.html#Simple-Statements">#</a><a id="Simple"></a>Simple Statements    </h2>

<p>The only kind of simple statement is an expression evaluated for its side-effects. Every simple statement must be terminated with a semicolon, unless it is the final statement in a block, in which case the semicolon is optional. But put the semicolon in anyway if the block takes up more than one line, because you may eventually add another line. Note that there are operators like <code>eval {}</code>, <code>sub {}</code>, and <code>do {}</code> that <i>look</i> like compound statements, but aren&#39;t--they&#39;re just TERMs in an expression--and thus need an explicit termination when used as the last item in a statement.</p>

<h2 id="Statement-Modifiers"><a class="permalink" href="perlsyn.html#Statement-Modifiers">#</a><a id="Statement"></a>Statement Modifiers         </h2>

<p>Any simple statement may optionally be followed by a <i>SINGLE</i> modifier, just before the terminating semicolon (or block ending). The possible modifiers are:</p>

<pre><code class="plaintext">if EXPR
unless EXPR
while EXPR
until EXPR
for LIST
foreach LIST
when EXPR</code></pre>

<p>The <code>EXPR</code> following the modifier is referred to as the &quot;condition&quot;. Its truth or falsehood determines how the modifier will behave.</p>

<p><code>if</code> executes the statement once <i>if</i> and only if the condition is true. <code>unless</code> is the opposite, it executes the statement <i>unless</i> the condition is true (that is, if the condition is false). See <a href="perldata.html#Scalar-values">&quot;Scalar values&quot; in perldata</a> for definitions of true and false.</p>

<pre><code>print &quot;Basset hounds got long ears&quot; if length $ear &gt;= 10;
go_outside() and play() unless $is_raining;</code></pre>

<p>The <code>for(each)</code> modifier is an iterator: it executes the statement once for each item in the LIST (with <code>$_</code> aliased to each item in turn). There is no syntax to specify a C-style for loop or a lexically scoped iteration variable in this form.</p>

<pre><code>print &quot;Hello $_!\n&quot; for qw(world Dolly nurse);</code></pre>

<p><code>while</code> repeats the statement <i>while</i> the condition is true. Postfix <code>while</code> has the same magic treatment of some kinds of condition that prefix <code>while</code> has. <code>until</code> does the opposite, it repeats the statement <i>until</i> the condition is true (or while the condition is false):</p>

<pre><code># Both of these count from 0 to 10.
print $i++ while $i &lt;= 10;
print $j++ until $j &gt;  10;</code></pre>

<p>The <code>while</code> and <code>until</code> modifiers have the usual &quot;<code>while</code> loop&quot; semantics (conditional evaluated first), except when applied to a <code>do</code>-BLOCK (or to the Perl4 <code>do</code>-SUBROUTINE statement), in which case the block executes once before the conditional is evaluated.</p>

<p>This is so that you can write loops like:</p>

<pre><code>do {
    $line = &lt;STDIN&gt;;
    ...
} until !defined($line) || $line eq &quot;.\n&quot;</code></pre>

<p>See <a href="perlfunc.html#do">&quot;do&quot; in perlfunc</a>. Note also that the loop control statements described later will <i>NOT</i> work in this construct, because modifiers don&#39;t take loop labels. Sorry. You can always put another block inside of it (for <code>next</code>/<code>redo</code>) or around it (for <code>last</code>) to do that sort of thing.   </p>

<p>For <code>next</code> or <code>redo</code>, just double the braces:</p>

<pre><code>do {{
    next if $x == $y;
    # do something here
}} until $x++ &gt; $z;</code></pre>

<p>For <code>last</code>, you have to be more elaborate and put braces around it: </p>

<pre><code>{
    do {
        last if $x == $y**2;
        # do something here
    } while $x++ &lt;= $z;
}</code></pre>

<p>If you need both <code>next</code> and <code>last</code>, you have to do both and also use a loop label:</p>

<pre><code>LOOP: {
    do {{
        next if $x == $y;
        last LOOP if $x == $y**2;
        # do something here
    }} until $x++ &gt; $z;
}</code></pre>

<p><b>NOTE:</b> The behaviour of a <code>my</code>, <code>state</code>, or <code>our</code> modified with a statement modifier conditional or loop construct (for example, <code>my $x if ...</code>) is <b>undefined</b>. The value of the <code>my</code> variable may be <code>undef</code>, any previously assigned value, or possibly anything else. Don&#39;t rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons. </p>

<p>The <code>when</code> modifier is an experimental feature that first appeared in Perl 5.14. To use it, you should include a <code>use v5.14</code> declaration. (Technically, it requires only the <code>switch</code> feature, but that aspect of it was not available before 5.14.) Operative only from within a <code>foreach</code> loop or a <code>given</code> block, it executes the statement only if the smartmatch <code>$_ ~~ <i>EXPR</i></code> is true. If the statement executes, it is followed by a <code>next</code> from inside a <code>foreach</code> and <code>break</code> from inside a <code>given</code>.</p>

<p>Under the current implementation, the <code>foreach</code> loop can be anywhere within the <code>when</code> modifier&#39;s dynamic scope, but must be within the <code>given</code> block&#39;s lexical scope. This restriction may be relaxed in a future release. See <a href="perlsyn.html#Switch-Statements">&quot;Switch Statements&quot;</a> below.</p>

<h2 id="Compound-Statements"><a class="permalink" href="perlsyn.html#Compound-Statements">#</a><a id="Compound"></a>Compound Statements               </h2>

<p>In Perl, a sequence of statements that defines a scope is called a block. Sometimes a block is delimited by the file containing it (in the case of a required file, or the program as a whole), and sometimes a block is delimited by the extent of a string (in the case of an eval).</p>

<p>But generally, a block is delimited by curly brackets, also known as braces. We will call this syntactic construct a BLOCK. Because enclosing braces are also the syntax for hash reference constructor expressions (see <a href="perlref.html">perlref</a>), you may occasionally need to disambiguate by placing a <code>;</code> immediately after an opening brace so that Perl realises the brace is the start of a block. You will more frequently need to disambiguate the other way, by placing a <code>+</code> immediately before an opening brace to force it to be interpreted as a hash reference constructor expression. It is considered good style to use these disambiguating mechanisms liberally, not only when Perl would otherwise guess incorrectly.</p>

<p>The following compound statements may be used to control flow:</p>

<pre><code class="plaintext">if (EXPR) BLOCK
if (EXPR) BLOCK else BLOCK
if (EXPR) BLOCK elsif (EXPR) BLOCK ...
if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK

unless (EXPR) BLOCK
unless (EXPR) BLOCK else BLOCK
unless (EXPR) BLOCK elsif (EXPR) BLOCK ...
unless (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK

given (EXPR) BLOCK

LABEL while (EXPR) BLOCK
LABEL while (EXPR) BLOCK continue BLOCK

LABEL until (EXPR) BLOCK
LABEL until (EXPR) BLOCK continue BLOCK

LABEL for (EXPR; EXPR; EXPR) BLOCK
LABEL for VAR (LIST) BLOCK
LABEL for VAR (LIST) BLOCK continue BLOCK

LABEL foreach (EXPR; EXPR; EXPR) BLOCK
LABEL foreach VAR (LIST) BLOCK
LABEL foreach VAR (LIST) BLOCK continue BLOCK

LABEL BLOCK
LABEL BLOCK continue BLOCK

PHASE BLOCK</code></pre>

<p>If enabled by the experimental <code>try</code> feature, the following may also be used</p>

<pre><code class="plaintext">try BLOCK catch (VAR) BLOCK</code></pre>

<p>The experimental <code>given</code> statement is <i>not automatically enabled</i>; see <a href="perlsyn.html#Switch-Statements">&quot;Switch Statements&quot;</a> below for how to do so, and the attendant caveats.</p>

<p>Unlike in C and Pascal, in Perl these are all defined in terms of BLOCKs, not statements. This means that the curly brackets are <i>required</i>--no dangling statements allowed. If you want to write conditionals without curly brackets, there are several other ways to do it. The following all do the same thing:</p>

<pre><code>if (!open(FOO)) { die &quot;Can&#39;t open $FOO: $!&quot; }
die &quot;Can&#39;t open $FOO: $!&quot; unless open(FOO);
open(FOO)  || die &quot;Can&#39;t open $FOO: $!&quot;;
open(FOO) ? () : die &quot;Can&#39;t open $FOO: $!&quot;;
    # a bit exotic, that last one</code></pre>

<p>The <code>if</code> statement is straightforward. Because BLOCKs are always bounded by curly brackets, there is never any ambiguity about which <code>if</code> an <code>else</code> goes with. If you use <code>unless</code> in place of <code>if</code>, the sense of the test is reversed. Like <code>if</code>, <code>unless</code> can be followed by <code>else</code>. <code>unless</code> can even be followed by one or more <code>elsif</code> statements, though you may want to think twice before using that particular language construct, as everyone reading your code will have to think at least twice before they can understand what&#39;s going on.</p>

<p>The <code>while</code> statement executes the block as long as the expression is true. The <code>until</code> statement executes the block as long as the expression is false. The LABEL is optional, and if present, consists of an identifier followed by a colon. The LABEL identifies the loop for the loop control statements <code>next</code>, <code>last</code>, and <code>redo</code>. If the LABEL is omitted, the loop control statement refers to the innermost enclosing loop. This may include dynamically searching through your call-stack at run time to find the LABEL. Such desperate behavior triggers a warning if you use the <code>use warnings</code> pragma or the <b>-w</b> flag.</p>

<p>If the condition expression of a <code>while</code> statement is based on any of a group of iterative expression types then it gets some magic treatment. The affected iterative expression types are <a href="perlfunc.html#readline-EXPR"><code>readline</code></a>, the <a href="perlop.html#I%2FO-Operators"><code>&lt;FILEHANDLE&gt;</code></a> input operator, <a href="perlfunc.html#readdir-DIRHANDLE"><code>readdir</code></a>, <a href="perlfunc.html#glob-EXPR"><code>glob</code></a>, the <a href="perlop.html#I%2FO-Operators"><code>&lt;PATTERN&gt;</code></a> globbing operator, and <a href="perlfunc.html#each-HASH"><code>each</code></a>. If the condition expression is one of these expression types, then the value yielded by the iterative operator will be implicitly assigned to <code>$_</code>. If the condition expression is one of these expression types or an explicit assignment of one of them to a scalar, then the condition actually tests for definedness of the expression&#39;s value, not for its regular truth value.</p>

<p>If there is a <code>continue</code> BLOCK, it is always executed just before the conditional is about to be evaluated again. Thus it can be used to increment a loop variable, even when the loop has been continued via the <code>next</code> statement.</p>

<p>When a block is preceded by a compilation phase keyword such as <code>BEGIN</code>, <code>END</code>, <code>INIT</code>, <code>CHECK</code>, or <code>UNITCHECK</code>, then the block will run only during the corresponding phase of execution. See <a href="perlmod.html">perlmod</a> for more details.</p>

<p>Extension modules can also hook into the Perl parser to define new kinds of compound statements. These are introduced by a keyword which the extension recognizes, and the syntax following the keyword is defined entirely by the extension. If you are an implementor, see <a href="perlapi.html#PL_keyword_plugin">&quot;PL_keyword_plugin&quot; in perlapi</a> for the mechanism. If you are using such a module, see the module&#39;s documentation for details of the syntax that it defines.</p>

<h2 id="Loop-Control"><a class="permalink" href="perlsyn.html#Loop-Control">#</a><a id="Loop"></a>Loop Control      </h2>

<p>The <code>next</code> command starts the next iteration of the loop:</p>

<pre><code>LINE: while (&lt;STDIN&gt;) {
    next LINE if /^#/;      # discard comments
    ...
}</code></pre>

<p>The <code>last</code> command immediately exits the loop in question. The <code>continue</code> block, if any, is not executed:</p>

<pre><code>LINE: while (&lt;STDIN&gt;) {
    last LINE if /^$/;      # exit when done with header
    ...
}</code></pre>

<p>The <code>redo</code> command restarts the loop block without evaluating the conditional again. The <code>continue</code> block, if any, is <i>not</i> executed. This command is normally used by programs that want to lie to themselves about what was just input.</p>

<p>For example, when processing a file like <i>/etc/termcap</i>. If your input lines might end in backslashes to indicate continuation, you want to skip ahead and get the next record.</p>

<pre><code>while (&lt;&gt;) {
    chomp;
    if (s/\\$//) {
        $_ .= &lt;&gt;;
        redo unless eof();
    }
    # now process $_
}</code></pre>

<p>which is Perl shorthand for the more explicitly written version:</p>

<pre><code>LINE: while (defined($line = &lt;ARGV&gt;)) {
    chomp($line);
    if ($line =~ s/\\$//) {
        $line .= &lt;ARGV&gt;;
        redo LINE unless eof(); # not eof(ARGV)!
    }
    # now process $line
}</code></pre>

<p>Note that if there were a <code>continue</code> block on the above code, it would get executed only on lines discarded by the regex (since redo skips the continue block). A continue block is often used to reset line counters or <code>m?pat?</code> one-time matches:</p>

<pre><code># inspired by :1,$g/fred/s//WILMA/
while (&lt;&gt;) {
    m?(fred)?    &amp;&amp; s//WILMA $1 WILMA/;
    m?(barney)?  &amp;&amp; s//BETTY $1 BETTY/;
    m?(homer)?   &amp;&amp; s//MARGE $1 MARGE/;
} continue {
    print &quot;$ARGV $.: $_&quot;;
    close ARGV  if eof;             # reset $.
    reset       if eof;             # reset ?pat?
}</code></pre>

<p>If the word <code>while</code> is replaced by the word <code>until</code>, the sense of the test is reversed, but the conditional is still tested before the first iteration.</p>

<p>Loop control statements don&#39;t work in an <code>if</code> or <code>unless</code>, since they aren&#39;t loops. You can double the braces to make them such, though.</p>

<pre><code>if (/pattern/) {{
    last if /fred/;
    next if /barney/; # same effect as &quot;last&quot;,
                      # but doesn&#39;t document as well
    # do something here
}}</code></pre>

<p>This is caused by the fact that a block by itself acts as a loop that executes once, see <a href="perlsyn.html#Basic-BLOCKs">&quot;Basic BLOCKs&quot;</a>.</p>

<p>The form <code>while/if BLOCK BLOCK</code>, available in Perl 4, is no longer available. Replace any occurrence of <code>if BLOCK</code> by <code>if (do BLOCK)</code>.</p>

<h2 id="For-Loops"><a class="permalink" href="perlsyn.html#For-Loops">#</a><a id="For"></a>For Loops  </h2>

<p>Perl&#39;s C-style <code>for</code> loop works like the corresponding <code>while</code> loop; that means that this:</p>

<pre><code>for ($i = 1; $i &lt; 10; $i++) {
    ...
}</code></pre>

<p>is the same as this:</p>

<pre><code>$i = 1;
while ($i &lt; 10) {
    ...
} continue {
    $i++;
}</code></pre>

<p>There is one minor difference: if variables are declared with <code>my</code> in the initialization section of the <code>for</code>, the lexical scope of those variables is exactly the <code>for</code> loop (the body of the loop and the control sections). To illustrate: </p>

<pre><code>my $i = &#39;samba&#39;;
for (my $i = 1; $i &lt;= 4; $i++) {
    print &quot;$i\n&quot;;
}
print &quot;$i\n&quot;;</code></pre>

<p>when executed, gives:</p>

<pre><code class="plaintext">1
2
3
4
samba</code></pre>

<p>As a special case, if the test in the <code>for</code> loop (or the corresponding <code>while</code> loop) is empty, it is treated as true. That is, both</p>

<pre><code>for (;;) {
    ...
}</code></pre>

<p>and</p>

<pre><code>while () {
    ...
}</code></pre>

<p>are treated as infinite loops.</p>

<p>Besides the normal array index looping, <code>for</code> can lend itself to many other interesting applications. Here&#39;s one that avoids the problem you get into if you explicitly test for end-of-file on an interactive file descriptor causing your program to appear to hang.   </p>

<pre><code>$on_a_tty = -t STDIN &amp;&amp; -t STDOUT;
sub prompt { print &quot;yes? &quot; if $on_a_tty }
for ( prompt(); &lt;STDIN&gt;; prompt() ) {
    # do something
}</code></pre>

<p>The condition expression of a <code>for</code> loop gets the same magic treatment of <code>readline</code> et al that the condition expression of a <code>while</code> loop gets.</p>

<h2 id="Foreach-Loops"><a class="permalink" href="perlsyn.html#Foreach-Loops">#</a><a id="Foreach"></a>Foreach Loops  </h2>

<p>The <code>foreach</code> loop iterates over a normal list value and sets the scalar variable VAR to be each element of the list in turn. If the variable is preceded with the keyword <code>my</code>, then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with <code>my</code>, it uses that variable instead of the global one, but it&#39;s still localized to the loop. This implicit localization occurs <i>only</i> in a <code>foreach</code> loop.  </p>

<p>The <code>foreach</code> keyword is actually a synonym for the <code>for</code> keyword, so you can use either. If VAR is omitted, <code>$_</code> is set to each value. </p>

<p>If any element of LIST is an lvalue, you can modify it by modifying VAR inside the loop. Conversely, if any element of LIST is NOT an lvalue, any attempt to modify that element will fail. In other words, the <code>foreach</code> loop index variable is an implicit alias for each item in the list that you&#39;re looping over. </p>

<p>If any part of LIST is an array, <code>foreach</code> will get very confused if you add or remove elements within the loop body, for example with <code>splice</code>. So don&#39;t do that. </p>

<p><code>foreach</code> probably won&#39;t do what you expect if VAR is a tied or other special variable. Don&#39;t do that either.</p>

<p>As of Perl 5.22, there is an experimental variant of this loop that accepts a variable preceded by a backslash for VAR, in which case the items in the LIST must be references. The backslashed variable will become an alias to each referenced item in the LIST, which must be of the correct type. The variable needn&#39;t be a scalar in this case, and the backslash may be followed by <code>my</code>. To use this form, you must enable the <code>refaliasing</code> feature via <code>use feature</code>. (See <a href="feature.html">feature</a>. See also <a href="perlref.html#Assigning-to-References">&quot;Assigning to References&quot; in perlref</a>.)</p>

<p>Examples:</p>

<pre><code>for (@ary) { s/foo/bar/ }

for my $elem (@elements) {
    $elem *= 2;
}

for $count (reverse(1..10), &quot;BOOM&quot;) {
    print $count, &quot;\n&quot;;
    sleep(1);
}

for (1..15) { print &quot;Merry Christmas\n&quot;; }

foreach $item (split(/:[\\\n:]*/, $ENV{TERMCAP})) {
    print &quot;Item: $item\n&quot;;
}

use feature &quot;refaliasing&quot;;
no warnings &quot;experimental::refaliasing&quot;;
foreach \my %hash (@array_of_hash_references) {
    # do something which each %hash
}</code></pre>

<p>Here&#39;s how a C programmer might code up a particular algorithm in Perl:</p>

<pre><code>for (my $i = 0; $i &lt; @ary1; $i++) {
    for (my $j = 0; $j &lt; @ary2; $j++) {
        if ($ary1[$i] &gt; $ary2[$j]) {
            last; # can&#39;t go to outer :-(
        }
        $ary1[$i] += $ary2[$j];
    }
    # this is where that last takes me
}</code></pre>

<p>Whereas here&#39;s how a Perl programmer more comfortable with the idiom might do it:</p>

<pre><code>OUTER: for my $wid (@ary1) {
INNER:   for my $jet (@ary2) {
            next OUTER if $wid &gt; $jet;
            $wid += $jet;
         }
      }</code></pre>

<p>See how much easier this is? It&#39;s cleaner, safer, and faster. It&#39;s cleaner because it&#39;s less noisy. It&#39;s safer because if code gets added between the inner and outer loops later on, the new code won&#39;t be accidentally executed. The <code>next</code> explicitly iterates the other loop rather than merely terminating the inner one. And it&#39;s faster because Perl executes a <code>foreach</code> statement more rapidly than it would the equivalent C-style <code>for</code> loop.</p>

<p>Perceptive Perl hackers may have noticed that a <code>for</code> loop has a return value, and that this value can be captured by wrapping the loop in a <code>do</code> block. The reward for this discovery is this cautionary advice: The return value of a <code>for</code> loop is unspecified and may change without notice. Do not rely on it.</p>

<h2 id="Try-Catch-Exception-Handling"><a class="permalink" href="perlsyn.html#Try-Catch-Exception-Handling">#</a><a id="Try"></a>Try Catch Exception Handling  </h2>

<p>The <code>try</code>/<code>catch</code> syntax provides control flow relating to exception handling. The <code>try</code> keyword introduces a block which will be executed when it is encountered, and the <code>catch</code> block provides code to handle any exception that may be thrown by the first.</p>

<pre><code>try {
    my $x = call_a_function();
    $x &lt; 100 or die &quot;Too big&quot;;
    send_output($x);
}
catch ($e) {
    warn &quot;Unable to output a value; $e&quot;;
}
print &quot;Finished\n&quot;;</code></pre>

<p>Here, the body of the <code>catch</code> block (i.e. the <code>warn</code> statement) will be executed if the initial block invokes the conditional <code>die</code>, or if either of the functions it invokes throws an uncaught exception. The <code>catch</code> block can inspect the <code>$e</code> lexical variable in this case to see what the exception was. If no exception was thrown then the <code>catch</code> block does not happen. In either case, execution will then continue from the following statement - in this example the <code>print</code>.</p>

<p>The <code>catch</code> keyword must be immediately followed by a variable declaration in parentheses, which introduces a new variable visible to the body of the subsequent block. Inside the block this variable will contain the exception value that was thrown by the code in the <code>try</code> block. It is not necessary to use the <code>my</code> keyword to declare this variable; this is implied (similar as it is for subroutine signatures).</p>

<p>Both the <code>try</code> and the <code>catch</code> blocks are permitted to contain control-flow expressions, such as <code>return</code>, <code>goto</code>, or <code>next</code>/<code>last</code>/<code>redo</code>. In all cases they behave as expected without warnings. In particular, a <code>return</code> expression inside the <code>try</code> block will make its entire containing function return - this is in contrast to its behaviour inside an <code>eval</code> block, where it would only make that block return.</p>

<p>Like other control-flow syntax, <code>try</code> and <code>catch</code> will yield the last evaluated value when placed as the final statement in a function or a <code>do</code> block. This permits the syntax to be used to create a value. In this case remember not to use the <code>return</code> expression, or that will cause the containing function to return.</p>

<pre><code>my $value = do {
    try {
        get_thing(@args);
    }
    catch ($e) {
        warn &quot;Unable to get thing - $e&quot;;
        $DEFAULT_THING;
    }
};</code></pre>

<p>As with other control-flow syntax, <code>try</code> blocks are not visible to <code>caller()</code> (just as for example, <code>while</code> or <code>foreach</code> loops are not). Successive levels of the <code>caller</code> result can see subroutine calls and <code>eval</code> blocks, because those affect the way that <code>return</code> would work. Since <code>try</code> blocks do not intercept <code>return</code>, they are not of interest to <code>caller</code>.</p>

<p>This syntax is currently experimental and must be enabled with <code>use feature &#39;try&#39;</code>. It emits a warning in the <code>experimental::try</code> category.</p>

<h2 id="Basic-BLOCKs"><a class="permalink" href="perlsyn.html#Basic-BLOCKs">#</a><a id="Basic"></a>Basic BLOCKs </h2>

<p>A BLOCK by itself (labeled or not) is semantically equivalent to a loop that executes once. Thus you can use any of the loop control statements in it to leave or restart the block. (Note that this is <i>NOT</i> true in <code>eval{}</code>, <code>sub{}</code>, or contrary to popular belief <code>do{}</code> blocks, which do <i>NOT</i> count as loops.) The <code>continue</code> block is optional.</p>

<p>The BLOCK construct can be used to emulate case structures.</p>

<pre><code>SWITCH: {
    if (/^abc/) { $abc = 1; last SWITCH; }
    if (/^def/) { $def = 1; last SWITCH; }
    if (/^xyz/) { $xyz = 1; last SWITCH; }
    $nothing = 1;
}</code></pre>

<p>You&#39;ll also find that <code>foreach</code> loop used to create a topicalizer and a switch:</p>

<pre><code>SWITCH:
for ($var) {
    if (/^abc/) { $abc = 1; last SWITCH; }
    if (/^def/) { $def = 1; last SWITCH; }
    if (/^xyz/) { $xyz = 1; last SWITCH; }
    $nothing = 1;
}</code></pre>

<p>Such constructs are quite frequently used, both because older versions of Perl had no official <code>switch</code> statement, and also because the new version described immediately below remains experimental and can sometimes be confusing.</p>

<h2 id="Switch-Statements"><a class="permalink" href="perlsyn.html#Switch-Statements">#</a><a id="Switch"></a>Switch Statements</h2>

<p>    </p>

<p>Starting from Perl 5.10.1 (well, 5.10.0, but it didn&#39;t work right), you can say</p>

<pre><code>use feature &quot;switch&quot;;</code></pre>

<p>to enable an experimental switch feature. This is loosely based on an old version of a Raku proposal, but it no longer resembles the Raku construct. You also get the switch feature whenever you declare that your code prefers to run under a version of Perl that is 5.10 or later. For example:</p>

<pre><code>use v5.14;</code></pre>

<p>Under the &quot;switch&quot; feature, Perl gains the experimental keywords <code>given</code>, <code>when</code>, <code>default</code>, <code>continue</code>, and <code>break</code>. Starting from Perl 5.16, one can prefix the switch keywords with <code>CORE::</code> to access the feature without a <code>use feature</code> statement. The keywords <code>given</code> and <code>when</code> are analogous to <code>switch</code> and <code>case</code> in other languages -- though <code>continue</code> is not -- so the code in the previous section could be rewritten as</p>

<pre><code>use v5.10.1;
for ($var) {
    when (/^abc/) { $abc = 1 }
    when (/^def/) { $def = 1 }
    when (/^xyz/) { $xyz = 1 }
    default       { $nothing = 1 }
}</code></pre>

<p>The <code>foreach</code> is the non-experimental way to set a topicalizer. If you wish to use the highly experimental <code>given</code>, that could be written like this:</p>

<pre><code>use v5.10.1;
given ($var) {
    when (/^abc/) { $abc = 1 }
    when (/^def/) { $def = 1 }
    when (/^xyz/) { $xyz = 1 }
    default       { $nothing = 1 }
}</code></pre>

<p>As of 5.14, that can also be written this way:</p>

<pre><code>use v5.14;
for ($var) {
    $abc = 1 when /^abc/;
    $def = 1 when /^def/;
    $xyz = 1 when /^xyz/;
    default { $nothing = 1 }
}</code></pre>

<p>Or if you don&#39;t care to play it safe, like this:</p>

<pre><code>use v5.14;
given ($var) {
    $abc = 1 when /^abc/;
    $def = 1 when /^def/;
    $xyz = 1 when /^xyz/;
    default { $nothing = 1 }
}</code></pre>

<p>The arguments to <code>given</code> and <code>when</code> are in scalar context, and <code>given</code> assigns the <code>$_</code> variable its topic value.</p>

<p>Exactly what the <i>EXPR</i> argument to <code>when</code> does is hard to describe precisely, but in general, it tries to guess what you want done. Sometimes it is interpreted as <code>$_ ~~ <i>EXPR</i></code>, and sometimes it is not. It also behaves differently when lexically enclosed by a <code>given</code> block than it does when dynamically enclosed by a <code>foreach</code> loop. The rules are far too difficult to understand to be described here. See <a href="perlsyn.html#Experimental-Details-on-given-and-when">&quot;Experimental Details on given and when&quot;</a> later on.</p>

<p>Due to an unfortunate bug in how <code>given</code> was implemented between Perl 5.10 and 5.16, under those implementations the version of <code>$_</code> governed by <code>given</code> is merely a lexically scoped copy of the original, not a dynamically scoped alias to the original, as it would be if it were a <code>foreach</code> or under both the original and the current Raku language specification. This bug was fixed in Perl 5.18 (and lexicalized <code>$_</code> itself was removed in Perl 5.24).</p>

<p>If your code still needs to run on older versions, stick to <code>foreach</code> for your topicalizer and you will be less unhappy.</p>

<h2 id="Goto"><a class="permalink" href="perlsyn.html#Goto">#</a>Goto </h2>

<p>Although not for the faint of heart, Perl does support a <code>goto</code> statement. There are three forms: <code>goto</code>-LABEL, <code>goto</code>-EXPR, and <code>goto</code>-&amp;NAME. A loop&#39;s LABEL is not actually a valid target for a <code>goto</code>; it&#39;s just the name of the loop.</p>

<p>The <code>goto</code>-LABEL form finds the statement labeled with LABEL and resumes execution there. It may not be used to go into any construct that requires initialization, such as a subroutine or a <code>foreach</code> loop. It also can&#39;t be used to go into a construct that is optimized away. It can be used to go almost anywhere else within the dynamic scope, including out of subroutines, but it&#39;s usually better to use some other construct such as <code>last</code> or <code>die</code>. The author of Perl has never felt the need to use this form of <code>goto</code> (in Perl, that is--C is another matter).</p>

<p>The <code>goto</code>-EXPR form expects a label name, whose scope will be resolved dynamically. This allows for computed <code>goto</code>s per FORTRAN, but isn&#39;t necessarily recommended if you&#39;re optimizing for maintainability:</p>

<pre><code>goto((&quot;FOO&quot;, &quot;BAR&quot;, &quot;GLARCH&quot;)[$i]);</code></pre>

<p>The <code>goto</code>-&amp;NAME form is highly magical, and substitutes a call to the named subroutine for the currently running subroutine. This is used by <code>AUTOLOAD()</code> subroutines that wish to load another subroutine and then pretend that the other subroutine had been called in the first place (except that any modifications to <code>@_</code> in the current subroutine are propagated to the other subroutine.) After the <code>goto</code>, not even <code>caller()</code> will be able to tell that this routine was called first.</p>

<p>In almost all cases like this, it&#39;s usually a far, far better idea to use the structured control flow mechanisms of <code>next</code>, <code>last</code>, or <code>redo</code> instead of resorting to a <code>goto</code>. For certain applications, the catch and throw pair of <code>eval{}</code> and die() for exception processing can also be a prudent approach.</p>

<h2 id="The-Ellipsis-Statement"><a class="permalink" href="perlsyn.html#The-Ellipsis-Statement">#</a><a id="The"></a>The Ellipsis Statement           </h2>

<p>Beginning in Perl 5.12, Perl accepts an ellipsis, &quot;<code>...</code>&quot;, as a placeholder for code that you haven&#39;t implemented yet. When Perl 5.12 or later encounters an ellipsis statement, it parses this without error, but if and when you should actually try to execute it, Perl throws an exception with the text <code>Unimplemented</code>:</p>

<pre><code>use v5.12;
sub unimplemented { ... }
eval { unimplemented() };
if ($@ =~ /^Unimplemented at /) {
    say &quot;I found an ellipsis!&quot;;
}</code></pre>

<p>You can only use the elliptical statement to stand in for a complete statement. Syntactically, &quot;<code>...;</code>&quot; is a complete statement, but, as with other kinds of semicolon-terminated statement, the semicolon may be omitted if &quot;<code>...</code>&quot; appears immediately before a closing brace. These examples show how the ellipsis works:</p>

<pre><code>use v5.12;
{ ... }
sub foo { ... }
...;
eval { ... };
sub somemeth {
    my $self = shift;
    ...;
}
$x = do {
    my $n;
    ...;
    say &quot;Hurrah!&quot;;
    $n;
};</code></pre>

<p>The elliptical statement cannot stand in for an expression that is part of a larger statement. These examples of attempts to use an ellipsis are syntax errors:</p>

<pre><code>use v5.12;

print ...;
open(my $fh, &quot;&gt;&quot;, &quot;/dev/passwd&quot;) or ...;
if ($condition &amp;&amp; ... ) { say &quot;Howdy&quot; };
... if $a &gt; $b;
say &quot;Cromulent&quot; if ...;
$flub = 5 + ...;</code></pre>

<p>There are some cases where Perl can&#39;t immediately tell the difference between an expression and a statement. For instance, the syntax for a block and an anonymous hash reference constructor look the same unless there&#39;s something in the braces to give Perl a hint. The ellipsis is a syntax error if Perl doesn&#39;t guess that the <code>{ ... }</code> is a block. Inside your block, you can use a <code>;</code> before the ellipsis to denote that the <code>{ ... }</code> is a block and not a hash reference constructor.</p>

<p>Note: Some folks colloquially refer to this bit of punctuation as a &quot;yada-yada&quot; or &quot;triple-dot&quot;, but its true name is actually an ellipsis.</p>

<h2 id="PODs:-Embedded-Documentation"><a class="permalink" href="perlsyn.html#PODs:-Embedded-Documentation">#</a><a id="PODs"></a>PODs: Embedded Documentation  </h2>

<p>Perl has a mechanism for intermixing documentation with source code. While it&#39;s expecting the beginning of a new statement, if the compiler encounters a line that begins with an equal sign and a word, like this</p>

<pre><code class="plaintext">=head1 Here There Be Pods!</code></pre>

<p>Then that text and all remaining text up through and including a line beginning with <code>=cut</code> will be ignored. The format of the intervening text is described in <a href="perlpod.html">perlpod</a>.</p>

<p>This allows you to intermix your source code and your documentation text freely, as in</p>

<pre><code>=item snazzle($)

The snazzle() function will behave in the most spectacular
form that you can possibly imagine, not even excepting
cybernetic pyrotechnics.

=cut back to the compiler, nuff of this pod stuff!

sub snazzle($) {
    my $thingie = shift;
    .........
}</code></pre>

<p>Note that pod translators should look at only paragraphs beginning with a pod directive (it makes parsing easier), whereas the compiler actually knows to look for pod escapes even in the middle of a paragraph. This means that the following secret stuff will be ignored by both the compiler and the translators.</p>

<pre><code>$a=3;
=secret stuff
 warn &quot;Neither POD nor CODE!?&quot;
=cut back
print &quot;got $a\n&quot;;</code></pre>

<p>You probably shouldn&#39;t rely upon the <code>warn()</code> being podded out forever. Not all pod translators are well-behaved in this regard, and perhaps the compiler will become pickier.</p>

<p>One may also use pod directives to quickly comment out a section of code.</p>

<h2 id="Plain-Old-Comments-(Not!)"><a class="permalink" href="perlsyn.html#Plain-Old-Comments-(Not!)">#</a><a id="Plain"></a><a id="Plain-Old-Comments-Not"></a>Plain Old Comments (Not!)     </h2>

<p>Perl can process line directives, much like the C preprocessor. Using this, one can control Perl&#39;s idea of filenames and line numbers in error or warning messages (especially for strings that are processed with <code>eval()</code>). The syntax for this mechanism is almost the same as for most C preprocessors: it matches the regular expression</p>

<pre><code class="plaintext"># example: &#39;# line 42 &quot;new_filename.plx&quot;&#39;
/^\#   \s*
  line \s+ (\d+)   \s*
  (?:\s(&quot;?)([^&quot;]+)\g2)? \s*
 $/x</code></pre>

<p>with <code>$1</code> being the line number for the next line, and <code>$3</code> being the optional filename (specified with or without quotes). Note that no whitespace may precede the <code>#</code>, unlike modern C preprocessors.</p>

<p>There is a fairly obvious gotcha included with the line directive: Debuggers and profilers will only show the last source line to appear at a particular line number in a given file. Care should be taken not to cause line number collisions in code you&#39;d like to debug later.</p>

<p>Here are some examples that you should be able to type into your command shell:</p>

<pre><code>% perl
# line 200 &quot;bzzzt&quot;
# the &#39;#&#39; on the previous line must be the first char on line
die &#39;foo&#39;;
__END__
foo at bzzzt line 201.

% perl
# line 200 &quot;bzzzt&quot;
eval qq[\n#line 2001 &quot;&quot;\ndie &#39;foo&#39;]; print $@;
__END__
foo at - line 2001.

% perl
eval qq[\n#line 200 &quot;foo bar&quot;\ndie &#39;foo&#39;]; print $@;
__END__
foo at foo bar line 200.

% perl
# line 345 &quot;goop&quot;
eval &quot;\n#line &quot; . __LINE__ . &#39; &quot;&#39; . __FILE__ .&quot;\&quot;\ndie &#39;foo&#39;&quot;;
print $@;
__END__
foo at goop line 345.</code></pre>

<h2 id="Experimental-Details-on-given-and-when"><a class="permalink" href="perlsyn.html#Experimental-Details-on-given-and-when">#</a><a id="Experimental"></a>Experimental Details on given and when</h2>

<p>As previously mentioned, the &quot;switch&quot; feature is considered highly experimental; it is subject to change with little notice. In particular, <code>when</code> has tricky behaviours that are expected to change to become less tricky in the future. Do not rely upon its current (mis)implementation. Before Perl 5.18, <code>given</code> also had tricky behaviours that you should still beware of if your code must run on older versions of Perl.</p>

<p>Here is a longer example of <code>given</code>:</p>

<pre><code>use feature &quot;:5.10&quot;;
given ($foo) {
    when (undef) {
        say &#39;$foo is undefined&#39;;
    }
    when (&quot;foo&quot;) {
        say &#39;$foo is the string &quot;foo&quot;&#39;;
    }
    when ([1,3,5,7,9]) {
        say &#39;$foo is an odd digit&#39;;
        continue; # Fall through
    }
    when ($_ &lt; 100) {
        say &#39;$foo is numerically less than 100&#39;;
    }
    when (\&amp;complicated_check) {
        say &#39;a complicated check for $foo is true&#39;;
    }
    default {
        die q(I don&#39;t know what to do with $foo);
    }
}</code></pre>

<p>Before Perl 5.18, <code>given(EXPR)</code> assigned the value of <i>EXPR</i> to merely a lexically scoped <i><b>copy</b></i> (!) of <code>$_</code>, not a dynamically scoped alias the way <code>foreach</code> does. That made it similar to</p>

<pre><code>do { my $_ = EXPR; ... }</code></pre>

<p>except that the block was automatically broken out of by a successful <code>when</code> or an explicit <code>break</code>. Because it was only a copy, and because it was only lexically scoped, not dynamically scoped, you could not do the things with it that you are used to in a <code>foreach</code> loop. In particular, it did not work for arbitrary function calls if those functions might try to access $_. Best stick to <code>foreach</code> for that.</p>

<p>Most of the power comes from the implicit smartmatching that can sometimes apply. Most of the time, <code>when(EXPR)</code> is treated as an implicit smartmatch of <code>$_</code>, that is, <code>$_ ~~ EXPR</code>. (See <a href="perlop.html#Smartmatch-Operator">&quot;Smartmatch Operator&quot; in perlop</a> for more information on smartmatching.) But when <i>EXPR</i> is one of the 10 exceptional cases (or things like them) listed below, it is used directly as a boolean.</p>

<dl>

<dt id="1."><a class="permalink" href="perlsyn.html#1.">#</a><a id="1"></a><a id="pod1"></a>1.</dt>
<dd>

<p>A user-defined subroutine call or a method invocation.</p>

</dd>
<dt id="2."><a class="permalink" href="perlsyn.html#2.">#</a><a id="2"></a><a id="pod2"></a>2.</dt>
<dd>

<p>A regular expression match in the form of <code>/REGEX/</code>, <code>$foo =~ /REGEX/</code>, or <code>$foo =~ EXPR</code>. Also, a negated regular expression match in the form <code>!/REGEX/</code>, <code>$foo !~ /REGEX/</code>, or <code>$foo !~ EXPR</code>.</p>

</dd>
<dt id="3."><a class="permalink" href="perlsyn.html#3.">#</a><a id="3"></a><a id="pod3"></a>3.</dt>
<dd>

<p>A smart match that uses an explicit <code>~~</code> operator, such as <code>EXPR ~~ EXPR</code>.</p>

<p><b>NOTE:</b> You will often have to use <code>$c ~~ $_</code> because the default case uses <code>$_ ~~ $c</code> , which is frequently the opposite of what you want.</p>

</dd>
<dt id="4."><a class="permalink" href="perlsyn.html#4.">#</a><a id="4"></a><a id="pod4"></a>4.</dt>
<dd>

<p>A boolean comparison operator such as <code>$_ &lt; 10</code> or <code>$x eq &quot;abc&quot;</code>. The relational operators that this applies to are the six numeric comparisons (<code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>, <code>&gt;=</code>, <code>==</code>, and <code>!=</code>), and the six string comparisons (<code>lt</code>, <code>gt</code>, <code>le</code>, <code>ge</code>, <code>eq</code>, and <code>ne</code>).</p>

</dd>
<dt id="5."><a class="permalink" href="perlsyn.html#5.">#</a><a id="5"></a><a id="pod5"></a>5.</dt>
<dd>

<p>At least the three builtin functions <code>defined(...)</code>, <code>exists(...)</code>, and <code>eof(...)</code>. We might someday add more of these later if we think of them.</p>

</dd>
<dt id="6."><a class="permalink" href="perlsyn.html#6.">#</a><a id="6"></a><a id="pod6"></a>6.</dt>
<dd>

<p>A negated expression, whether <code>!(EXPR)</code> or <code>not(EXPR)</code>, or a logical exclusive-or, <code>(EXPR1) xor (EXPR2)</code>. The bitwise versions (<code>~</code> and <code>^</code>) are not included.</p>

</dd>
<dt id="7."><a class="permalink" href="perlsyn.html#7.">#</a><a id="7"></a><a id="pod7"></a>7.</dt>
<dd>

<p>A filetest operator, with exactly 4 exceptions: <code>-s</code>, <code>-M</code>, <code>-A</code>, and <code>-C</code>, as these return numerical values, not boolean ones. The <code>-z</code> filetest operator is not included in the exception list.</p>

</dd>
<dt id="8."><a class="permalink" href="perlsyn.html#8.">#</a><a id="8"></a><a id="pod8"></a>8.</dt>
<dd>

<p>The <code>..</code> and <code>...</code> flip-flop operators. Note that the <code>...</code> flip-flop operator is completely different from the <code>...</code> elliptical statement just described.</p>

</dd>
</dl>

<p>In those 8 cases above, the value of EXPR is used directly as a boolean, so no smartmatching is done. You may think of <code>when</code> as a smartsmartmatch.</p>

<p>Furthermore, Perl inspects the operands of logical operators to decide whether to use smartmatching for each one by applying the above test to the operands:</p>

<dl>

<dt id="9."><a class="permalink" href="perlsyn.html#9.">#</a><a id="9"></a><a id="pod9"></a>9.</dt>
<dd>

<p>If EXPR is <code>EXPR1 &amp;&amp; EXPR2</code> or <code>EXPR1 and EXPR2</code>, the test is applied <i>recursively</i> to both EXPR1 and EXPR2. Only if <i>both</i> operands also pass the test, <i>recursively</i>, will the expression be treated as boolean. Otherwise, smartmatching is used.</p>

</dd>
<dt id="10."><a class="permalink" href="perlsyn.html#10.">#</a><a id="10"></a><a id="pod10"></a>10.</dt>
<dd>

<p>If EXPR is <code>EXPR1 || EXPR2</code>, <code>EXPR1 // EXPR2</code>, or <code>EXPR1 or EXPR2</code>, the test is applied <i>recursively</i> to EXPR1 only (which might itself be a higher-precedence AND operator, for example, and thus subject to the previous rule), not to EXPR2. If EXPR1 is to use smartmatching, then EXPR2 also does so, no matter what EXPR2 contains. But if EXPR2 does not get to use smartmatching, then the second argument will not be either. This is quite different from the <code>&amp;&amp;</code> case just described, so be careful.</p>

</dd>
</dl>

<p>These rules are complicated, but the goal is for them to do what you want (even if you don&#39;t quite understand why they are doing it). For example:</p>

<pre><code>when (/^\d+$/ &amp;&amp; $_ &lt; 75) { ... }</code></pre>

<p>will be treated as a boolean match because the rules say both a regex match and an explicit test on <code>$_</code> will be treated as boolean.</p>

<p>Also:</p>

<pre><code class="plaintext">when ([qw(foo bar)] &amp;&amp; /baz/) { ... }</code></pre>

<p>will use smartmatching because only <i>one</i> of the operands is a boolean: the other uses smartmatching, and that wins.</p>

<p>Further:</p>

<pre><code class="plaintext">when ([qw(foo bar)] || /^baz/) { ... }</code></pre>

<p>will use smart matching (only the first operand is considered), whereas</p>

<pre><code class="plaintext">when (/^baz/ || [qw(foo bar)]) { ... }</code></pre>

<p>will test only the regex, which causes both operands to be treated as boolean. Watch out for this one, then, because an arrayref is always a true value, which makes it effectively redundant. Not a good idea.</p>

<p>Tautologous boolean operators are still going to be optimized away. Don&#39;t be tempted to write</p>

<pre><code class="plaintext">when (&quot;foo&quot; or &quot;bar&quot;) { ... }</code></pre>

<p>This will optimize down to <code>&quot;foo&quot;</code>, so <code>&quot;bar&quot;</code> will never be considered (even though the rules say to use a smartmatch on <code>&quot;foo&quot;</code>). For an alternation like this, an array ref will work, because this will instigate smartmatching:</p>

<pre><code class="plaintext">when ([qw(foo bar)] { ... }</code></pre>

<p>This is somewhat equivalent to the C-style switch statement&#39;s fallthrough functionality (not to be confused with <i>Perl&#39;s</i> fallthrough functionality--see below), wherein the same block is used for several <code>case</code> statements.</p>

<p>Another useful shortcut is that, if you use a literal array or hash as the argument to <code>given</code>, it is turned into a reference. So <code>given(@foo)</code> is the same as <code>given(\@foo)</code>, for example.</p>

<p><code>default</code> behaves exactly like <code>when(1 == 1)</code>, which is to say that it always matches.</p>

<h3 id="Breaking-out"><a class="permalink" href="perlsyn.html#Breaking-out">#</a><a id="Breaking"></a>Breaking out</h3>

<p>You can use the <code>break</code> keyword to break out of the enclosing <code>given</code> block. Every <code>when</code> block is implicitly ended with a <code>break</code>.</p>

<h3 id="Fall-through"><a class="permalink" href="perlsyn.html#Fall-through">#</a><a id="Fall"></a>Fall-through</h3>

<p>You can use the <code>continue</code> keyword to fall through from one case to the next immediate <code>when</code> or <code>default</code>:</p>

<pre><code>given($foo) {
    when (/x/) { say &#39;$foo contains an x&#39;; continue }
    when (/y/) { say &#39;$foo contains a y&#39;            }
    default    { say &#39;$foo does not contain a y&#39;    }
}</code></pre>

<h3 id="Return-value"><a class="permalink" href="perlsyn.html#Return-value">#</a><a id="Return"></a>Return value</h3>

<p>When a <code>given</code> statement is also a valid expression (for example, when it&#39;s the last statement of a block), it evaluates to:</p>

<ul>

<li><p>An empty list as soon as an explicit <code>break</code> is encountered.</p>

</li>
<li><p>The value of the last evaluated expression of the successful <code>when</code>/<code>default</code> clause, if there happens to be one.</p>

</li>
<li><p>The value of the last evaluated expression of the <code>given</code> block if no condition is true.</p>

</li>
</ul>

<p>In both last cases, the last expression is evaluated in the context that was applied to the <code>given</code> block.</p>

<p>Note that, unlike <code>if</code> and <code>unless</code>, failed <code>when</code> statements always evaluate to an empty list.</p>

<pre><code>my $price = do {
    given ($item) {
        when ([&quot;pear&quot;, &quot;apple&quot;]) { 1 }
        break when &quot;vote&quot;;      # My vote cannot be bought
        1e10  when /Mona Lisa/;
        &quot;unknown&quot;;
    }
};</code></pre>

<p>Currently, <code>given</code> blocks can&#39;t always be used as proper expressions. This may be addressed in a future version of Perl.</p>

<h3 id="Switching-in-a-loop"><a class="permalink" href="perlsyn.html#Switching-in-a-loop">#</a><a id="Switching"></a>Switching in a loop</h3>

<p>Instead of using <code>given()</code>, you can use a <code>foreach()</code> loop. For example, here&#39;s one way to count how many times a particular string occurs in an array:</p>

<pre><code>use v5.10.1;
my $count = 0;
for (@array) {
    when (&quot;foo&quot;) { ++$count }
}
print &quot;\@array contains $count copies of &#39;foo&#39;\n&quot;;</code></pre>

<p>Or in a more recent version:</p>

<pre><code>use v5.14;
my $count = 0;
for (@array) {
    ++$count when &quot;foo&quot;;
}
print &quot;\@array contains $count copies of &#39;foo&#39;\n&quot;;</code></pre>

<p>At the end of all <code>when</code> blocks, there is an implicit <code>next</code>. You can override that with an explicit <code>last</code> if you&#39;re interested in only the first match alone.</p>

<p>This doesn&#39;t work if you explicitly specify a loop variable, as in <code>for $item (@array)</code>. You have to use the default variable <code>$_</code>.</p>

<h3 id="Differences-from-Raku"><a class="permalink" href="perlsyn.html#Differences-from-Raku">#</a><a id="Differences"></a>Differences from Raku</h3>

<p>The Perl 5 smartmatch and <code>given</code>/<code>when</code> constructs are not compatible with their Raku analogues. The most visible difference and least important difference is that, in Perl 5, parentheses are required around the argument to <code>given()</code> and <code>when()</code> (except when this last one is used as a statement modifier). Parentheses in Raku are always optional in a control construct such as <code>if()</code>, <code>while()</code>, or <code>when()</code>; they can&#39;t be made optional in Perl 5 without a great deal of potential confusion, because Perl 5 would parse the expression</p>

<pre><code>given $foo {
    ...
}</code></pre>

<p>as though the argument to <code>given</code> were an element of the hash <code>%foo</code>, interpreting the braces as hash-element syntax.</p>

<p>However, their are many, many other differences. For example, this works in Perl 5:</p>

<pre><code>use v5.12;
my @primary = (&quot;red&quot;, &quot;blue&quot;, &quot;green&quot;);

if (@primary ~~ &quot;red&quot;) {
    say &quot;primary smartmatches red&quot;;
}

if (&quot;red&quot; ~~ @primary) {
    say &quot;red smartmatches primary&quot;;
}

say &quot;that&#39;s all, folks!&quot;;</code></pre>

<p>But it doesn&#39;t work at all in Raku. Instead, you should use the (parallelizable) <code>any</code> operator:</p>

<pre><code>if any(@primary) eq &quot;red&quot; {
    say &quot;primary smartmatches red&quot;;
}

if &quot;red&quot; eq any(@primary) {
    say &quot;red smartmatches primary&quot;;
}</code></pre>

<p>The table of smartmatches in <a href="perlop.html#Smartmatch-Operator">&quot;Smartmatch Operator&quot; in perlop</a> is not identical to that proposed by the Raku specification, mainly due to differences between Raku&#39;s and Perl 5&#39;s data models, but also because the Raku spec has changed since Perl 5 rushed into early adoption.</p>

<p>In Raku, <code>when()</code> will always do an implicit smartmatch with its argument, while in Perl 5 it is convenient (albeit potentially confusing) to suppress this implicit smartmatch in various rather loosely-defined situations, as roughly outlined above. (The difference is largely because Perl 5 does not have, even internally, a boolean type.)</p>


      </div>
      <div id="footer">
        <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p>

<p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p>


      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
    <script src="../highlight.pack.js"></script>
    <script>hljs.highlightAll();</script>
  </body>
</html>
